package com.heima.comment.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.apis.use.IUseClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.util.ThreadLocalUtil;
import com.heima.comment.vo.CommentRepayVo;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CacheService cacheService;


    @Autowired
    private IUseClient iUseClient;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        Query limit = Query.query(Criteria.where("commentId").
                        is(dto.getCommentId()).
                        and("updatedTime").
                        lt(dto.getMinDate())).
                with(Sort.by(Sort.Direction.DESC, "updatedTime"))
                .limit(10);
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(limit, ApCommentRepay.class);

        List<CommentRepayVo> commentVoList = apCommentRepays.stream().map(apCommentRepay -> {

            Query queryApCommentLike = Query.query(Criteria.where("authorId")
                    .is(ThreadLocalUtil.get())
                    .and("commentId")
                    .is(apCommentRepay.getId()));
            ApCommentRepayLike apCommentLike = mongoTemplate.findOne(queryApCommentLike, ApCommentRepayLike.class);

            CommentRepayVo commentRepayVo = new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, commentRepayVo);
            if (apCommentLike == null) {
                commentRepayVo.setOperation(0);
            } else {
                commentRepayVo.setOperation(apCommentLike.getOperation());
            }
            return commentRepayVo;

        }).collect(Collectors.toList());

        return ResponseResult.okResult(commentVoList);
    }


    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {

        if (!auditText(dto.getContent())) {
            //审核未通过
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult userResponseResult = iUseClient.findById(ThreadLocalUtil.get());
        if (userResponseResult.getCode()!=200 || userResponseResult.getData()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Object userJsonObject = userResponseResult.getData();
        String userJson = JSON.toJSONString(userJsonObject);
        ApUser user= JSON.parseObject(userJson,ApUser.class);


        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(ThreadLocalUtil.get());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);

        Query id = Query.query(Criteria.where("_id").is(dto.getCommentId()));

        ApComment apCommentINDb = mongoTemplate.findOne(id, ApComment.class);
        apCommentINDb.setReply(apCommentINDb.getReply()+1);
        apCommentINDb.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentINDb);

        return ResponseResult.okResult("评论成功");
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        Query queryApComment = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
        ApCommentRepay apCommentRepayInDb= mongoTemplate.findOne(queryApComment, ApCommentRepay.class);
        if (dto.getOperation()==0){
            apCommentRepayInDb.setLikes(apCommentRepayInDb.getLikes()-1);
        } else if (dto.getOperation() == 1) {
            apCommentRepayInDb.setLikes(apCommentRepayInDb.getLikes()+1);
        }
        //更新更新时间
        apCommentRepayInDb.setUpdatedTime(new Date());


        mongoTemplate.save(apCommentRepayInDb);


        Query queryApCommentLike = Query.query(Criteria.where("authorId").is(ThreadLocalUtil.get()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLikeInDb= mongoTemplate.findOne(queryApCommentLike, ApCommentRepayLike.class);
        if(apCommentRepayLikeInDb==null){
            apCommentRepayLikeInDb = new ApCommentRepayLike();
            apCommentRepayLikeInDb.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLikeInDb.setAuthorId(ThreadLocalUtil.get());
            apCommentRepayLikeInDb.setOperation(Integer.valueOf(dto.getOperation()));
        }else {
            apCommentRepayLikeInDb.setOperation(Integer.valueOf(dto.getOperation()));
        }
        mongoTemplate.save(apCommentRepayLikeInDb);
        HashMap hashMap = new HashMap();
        hashMap.put("likes",apCommentRepayInDb.getLikes());


        return ResponseResult.okResult(hashMap);
    }



    private boolean auditText(String text){

        Set<String> wmSensitiveset = cacheService.setMembers(WemediaConstants.CATCH_KEY_SENSITIVE);
        SensitiveWordUtil.initMap(wmSensitiveset);
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(text);
        if (!stringIntegerMap.isEmpty()){
            return false;
        }

        return true;
    }
}
